import earcut from "./earcut.js";
import { attach } from "./utils.js";

const canvas = document.querySelector("canvas");
// const ctx = canvas.getContext("2d");
const gl = canvas.getContext('webgl')

const vertex = `
  #define PI 3.1415926535897932384626433832795
  attribute vec2 position;
  varying vec3 color;
  uniform float u_time;
  void main() {
    gl_PointSize = 1.0;
    // color = vec3(0.0, 0.7 + position * 0.3 * 0.1666666);
    color = vec3(0.0, 0.7 + 0.3 * sin(position * 0.1666666 + u_time));
    gl_Position = vec4(position * 0.1666666, 0.0, 1.0);
  }
`;


  const fragment = `
  precision mediump float;
  varying vec3 color;
  void main()
  {
    gl_FragColor = vec4(color, 1.0);
  }    
`;

const program = attach(gl, vertex, fragment)

function draw(vertices) {
  const points = vertices.flat()
  // console.log(points)
  const triangles = earcut(points)

  // console.log(points, triangles)
  
  const position = new Float32Array(points)
  const cells = new Uint16Array(triangles)
  
  const pointBuffer = gl.createBuffer()
  gl.bindBuffer(gl.ARRAY_BUFFER, pointBuffer)
  gl.bufferData(gl.ARRAY_BUFFER, position, gl.STATIC_DRAW)
  
  const vPosition = gl.getAttribLocation(program, 'position')
  gl.vertexAttribPointer(vPosition, 2, gl.FLOAT, false, 0, 0)
  gl.enableVertexAttribArray(vPosition)
  
  const cellsBuffer = gl.createBuffer()
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cellsBuffer)
  gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, cells, gl.STATIC_DRAW)
  
  gl.drawArrays(gl.LINE_LOOP, 0, vertices.length)
  gl.drawElements(gl.TRIANGLES, cells.length, gl.UNSIGNED_SHORT, 0)
}

const vertices1 = [
  [-5, 5],
  [-1, 5],
  [-1, 3],
  [1, 3],
  [1, 5],
  [5, 5],
  [5, 3],
  [3, 3],
  [3, 1],
  [-3, 1],
  [-3, 3],
  [-5, 3]
]

const vertices2 = [
  [-5, -3],
  [-5, -1],
  [5, -1],
  [5, -3],
  [1, -3],
  [1, -5], // 你妈这里写成 [1.-5], 我说怎么出现了一个-4，还以为是flat方法错了
  [-1, -5],
  [-1, -3]
]

let startTime = performance.now()

function update() {
  gl.clear(gl.COLOR_BUFFER_BIT)
  const u_time = (performance.now() - startTime) / 1000
  const loc = gl.getUniformLocation(program, 'u_time')
  gl.uniform1f(loc, u_time)
  draw(vertices1)
  draw(vertices2)
  requestAnimationFrame(update)
}

requestAnimationFrame(update)

// const url = canvas.toDataURL('image/png')

// console.log(url)